package com.own.core.function.add;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.markup.html.panel.FeedbackPanel;

import com.own.core.html.ListViewObject;
import com.own.core.html.form.OwnForm;
import com.own.core.html.form.Label.OwnLabel;
import com.own.core.html.form.button.OwnAjaxButton;
import com.own.core.html.form.button.OwnButton;
import com.own.core.html.panel.OwnPanel;
import com.own.util.model.OwnCompoundPropertyModel;
import com.own.core.object.Dao;
import com.own.core.object.lookup.Lookup;
import com.own.core.operation.DbOperation;
import com.own.util.FieldUtil;
import com.own.util.ResourceUtil;

public class AddObjectPanel extends OwnPanel {

	OwnForm form;
	OwnButton submitBut;
	ListViewObject listview;

	public AddObjectPanel(OwnPanel parent) {
		super("content");
setParentPanel(parent);
	}

	public void draw(Dao obj) {

		this.add(new OwnLabel("header", ResourceUtil.getResource(obj)));
		form = new OwnForm() {

			protected void onSubmit() {
				try {
					Dao dao = (Dao) getModelObject();
					boolean isAdd = dao.getId() == 0;

					DbOperation.getME().saveOrUpdate(dao);

					// listener add
			
					if (isAdd) {
						getOwnPage().generateControllerObject().afterRenderAdd(
								dao);
					} else {
						getOwnPage().generateControllerObject()
								.afterRenderEdit(dao);
					}
				} catch (Exception e) {

				}

			}

		};

		add(form);
		Field[] fields = obj.getClass().getDeclaredFields();
		if (Lookup.class.isAssignableFrom(obj.getClass())) {
			fields = FieldUtil.getAllFields(obj.getClass());
		}
		OwnCompoundPropertyModel model = new OwnCompoundPropertyModel(obj);
		List list = Arrays.asList(fields);

		listview = new ListViewObject(model, list, form);
		form.add(listview);
		final FeedbackPanel feedbackpanel = new FeedbackPanel("feedbackPanel");
		feedbackpanel.setOutputMarkupId(true);
		form.add(feedbackpanel);

		OwnAjaxButton submitBut = new OwnAjaxButton("submit", feedbackpanel) {

			@Override
			protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
				if (getMainComponent() != null) {
					target.addComponent(getMainComponent());
				}

				getModalWindow().closeCurrent(target);

			}

		};

		form.add(submitBut);

		OwnAjaxButton cancelBut = new OwnAjaxButton("cancel") {

			@Override
			protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
				getModalWindow().closeCurrent(target);

			}

			@Override
			protected void onError(final AjaxRequestTarget target,
					final Form form) {
				getModalWindow().closeCurrent(target);
			}

		};
		form.add(cancelBut);

		form.setModel(model);

	}

	public Map<String, FormComponent> getComponentMap() {
		return listview.getComponentMap();
	}
}
